package thesis.filesharing.bo.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import thesis.filesharing.bo.LecturerBO;
import thesis.filesharing.common.exception.functional.InvalidArgumentException;
import thesis.filesharing.common.exception.functional.ObjectNotFoundException;
import thesis.filesharing.common.valueobjects.SearchLecturerValueObject;
import thesis.filesharing.dao.LecturerDAO;
import thesis.filesharing.model.Lecturer;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@Service
public class LecturerBOImpl implements LecturerBO {
	
	@Autowired
	private LecturerDAO lecturerDAO;
	
	@Override
	public Lecturer findLecturerById(String lecturerId) {
		return lecturerDAO.findLecturerById(lecturerId);
	}

	@Override
	public Lecturer saveLecturer(Lecturer lecturer) {
		return lecturerDAO.saveLecturer(lecturer);
	}

	@Override
	public Lecturer findLecturerByEmail(String lecturerEmail) {
		return lecturerDAO.findLecturerByEmail(lecturerEmail);
	}

	@Override
	public List<Lecturer> listLecturers(int page, int pageSize) {
		if (page < 1 || pageSize < 1) {
			List<String> errs = new ArrayList<String>();
			if (page < 1) errs.add("page");
			if (pageSize < 1) errs.add("pageSize");
			throw new InvalidArgumentException(null, errs);
		}
		return lecturerDAO.listLecturers(page, pageSize);
	}

	@Override
	public int countLecturers() {
		return lecturerDAO.countLecturers();
	}

	@Override
	public void deleteLecturer(String key) {
		Key lecturerKey = KeyFactory.stringToKey(key);
		Lecturer l = lecturerDAO.findLecturerByKey(lecturerKey);
		if (l == null) {
			throw new ObjectNotFoundException(new Exception("Lecturer could not be found"), Lecturer.class);
		}
		lecturerDAO.deleteLecturer(lecturerKey);
	}

	@Override
	public Lecturer findLecturerByKey(Key lecturerKey) {
		return lecturerDAO.findLecturerByKey(lecturerKey);
	}

	@Override
	public Lecturer updateLecturer(Lecturer lecturer) {
		return lecturerDAO.updateLecturer(lecturer);
	}

	@Override
	public boolean isEmailDuplicatedWithOrtherLecturer(String lecturerEmail, String lecturerKey) {
		return lecturerDAO.isEmailDuplicatedWithOrtherLecturer(lecturerEmail, KeyFactory.stringToKey(lecturerKey));
	}

	@Override
	public int countFoundLecturers(SearchLecturerValueObject searchObj) {
		return lecturerDAO.countFoundLecturers(searchObj);
	}

	@Override
	public List<Lecturer> searchLecturers(SearchLecturerValueObject searchObj, int page, int pageSize) {
		if (page <= 0 || pageSize <= 0) {
			throw new InvalidArgumentException();
		}
		return lecturerDAO.searchLecturers(searchObj, page, pageSize);
	}
}
